package com.gf.forcesystem.websocket;

import com.gf.forcesystem.model.dto.BaseMessage;
import com.gf.framework.common.json.GfJsonMapper;
import io.swagger.annotations.Api;
import lombok.extern.slf4j.Slf4j;
import org.springframework.stereotype.Component;

import javax.websocket.OnClose;
import javax.websocket.OnMessage;
import javax.websocket.OnOpen;
import javax.websocket.Session;
import javax.websocket.server.ServerEndpoint;

/**
 * @author gaofei
 * @date 2022/6/20 22:20
 * 兵力导调软件websocket接口
 */
@Component
@Slf4j
@Api(tags = "兵力导调软件websocket接口")
@ServerEndpoint("/ws/forcescene")
public class ForeSceneWebsocketServiceImpl {
    private volatile static Session session;

    @OnOpen
    public void onOpen(Session session) throws Exception{
        synchronized (ForeSceneWebsocketServiceImpl.class) {
            if (ForeSceneWebsocketServiceImpl.session != null) {
                session.getBasicRemote().sendText("已有兵力导调软件接入，不可重复接入");
                session.close();
                return;
            }
            else {
                ForeSceneWebsocketServiceImpl.session = session;
            }
        }

        log.info("兵力导调软件websocket链接成功");
    }

    @OnMessage
    public void message(Session session, String message) {
        if (!session.equals(ForeSceneWebsocketServiceImpl.session))
            return;

        BaseMessage baseMessage = GfJsonMapper.string2Obj(message, BaseMessage.class);
        if (baseMessage != null) {
            // todo 广播消息
        }
    }

    @OnClose
    public void close() {
        ForeSceneWebsocketServiceImpl.session = null;
        log.info("兵力导调软件websocket断开");
    }
}
